#-*- coding:utf-8 -*-
import sys
from configurations.cpp import cp
sys.path.insert(0,cp.get("python_lib", "cv2_lib"))
import os
import cv2
import time
import threading
from utils.timecontroller import tc
from loggingconf.log import logger

class Camera():
    # capture set get the configurations from the file of config.txt
    def __init__(self,camera_id,storepath):
        self.frame = None
        self.thread = None
        self.alreadyinitialized = False
        self.width = cp.getint("camera_dev", "width")
        self.height = cp.getint("camera_dev", "height")
        self.camera_id = camera_id
        # 配置摄像头参数
        self.cap = cv2.VideoCapture(self.camera_id)
        self.cap.set(3,self.height)
        self.cap.set(4,self.width)
        self.sample_rate = cp.getint("camera_dev","sample_rate")
        time.sleep(1)
        self.storepath = storepath

    def initialize(self):
        if(self.alreadyinitialized):
            logger.info("camera"+str(self.camera_id)+" already initialized")
            return
        logger.info("initalize the camera%d to start"%(self.camera_id))

        if self.frame == None:
            self.thread = threading.Thread(target=self._thread)
            self.thread.start()
        else:
            logger.info("the camera already initalized")

    def _thread(self):
        logger.info("the camera thread start")
        while True:
            ret,frame = self.cap.read()
            if ret:
                self.frame = frame
                cv2.imshow("video%d"%self.camera_id,self.frame)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                tostore,timestamp,sub = tc.isInRecord2()
                if tostore:
                    subfolder = os.path.join(self.storepath,sub)
                    if(not os.path.exists(subfolder)):
                        os.mkdir(subfolder)
                    filename = "%d.jpg"%timestamp
                    absolute_filepath = os.path.join(subfolder,filename)
                    logger.info(absolute_filepath.encode("utf-8"))
                    cv2.imwrite(absolute_filepath,self.frame)
            time.sleep(1.0/self.sample_rate)